package com.acme.bankapp.email;

import java.util.ArrayList;
import java.util.List;

/**
 * This is synchronized variant of queue
 * 
 * @author Anton Kotov
 * 
 */
public class Queue {

    public Queue() {
    }

    public synchronized Email pop() throws QueueClosedAndEmptyException {
	try {
	    while (queue.isEmpty()) {
		wait();
		if (isClosed && isEmpty()) {
		    // we simply exit from queue.pop() when thread waits, queue
		    // is empty and we close queue
		    throw new QueueClosedAndEmptyException();
		}
	    }
	    return (Email) queue.remove(0);
	} catch (InterruptedException e) {
	    e.printStackTrace();
	    return null;
	}
    }

    @SuppressWarnings("unchecked")
    public synchronized void push(Email email) throws QueueClosedException {
	if (isClosed) {
	    throw new QueueClosedException();
	}
	queue.add(email);
	notify();
    }

    public synchronized boolean isEmpty() {
	return queue.isEmpty();
    }

    public synchronized void close() {
	isClosed = true;
	notifyAll();
    }

    public synchronized boolean isClosed() {
	return isClosed;
    }

    @SuppressWarnings("rawtypes")
    private List queue = new ArrayList();

    private boolean isClosed = false;

}
